import { request } from "../config/axios.config";
import * as mock from './mock/user'
import * as env from '../config/env.config'


const login = async (uname, password) => {
    return env.ENV === env.pro ? request.post('/user/login', {
        uname, password
    }) : mock.login()
}

const whoami = async () => {
    return env.ENV === env.pro ? request.get('/user/getUserInfo') : mock.whoami()
}

const setToken = ({ token }) => {
    sessionStorage.setItem('token', token)
}

const getToken = () => {
    return sessionStorage.getItem('token')
}

const setLogged = () => {
    console.log('setLogged');
    sessionStorage.setItem('logged', true)
}

const getLogged = async (refetch) => {
    if (refetch) {
        const data = await whoami();
        if (data.code !== 200) return
        sessionStorage.setItem('userInfo', JSON.stringify(data.data))
    }
    return getToken()
}

const getUserInfo = () => {
    return JSON.parse(sessionStorage.getItem('userInfo'))
}

const logout = () => {
    return env.ENV === env.pro ? request.get('/user/logout') : mock.logout()
}

const isAdmin = () => {
    return getUserInfo().type === '1'
}

export {
    login,
    whoami,
    logout,
    isAdmin,
    setToken,
    setLogged,
    getLogged,
    getUserInfo
}